package com.nananer7.servlet;

import com.nananer7.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.setCharacterEncoding("utf-8");

        //得到表单提交的内容
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        String psw =new UserDao().findPswByUsername(username);

        HttpSession session = request.getSession();

        //判空
        if(username ==null){
            session.setAttribute("logmsg","用户名不能为空");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }else if(password == null){
            session.setAttribute("logmsg","密码不能为空");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }else if(psw ==null){
            session.setAttribute("logmsg", "用户不存在！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }else if(psw!=null&&!psw.equals(password)){
            session.setAttribute("logmsg", "密码错误请重新输入！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }else if(psw.equals(password)){
            session.setAttribute("username",username);
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        }
    }
}
